package com.wyx.SpringSecurityConfig;


import com.wyx.utils.PasswordEncryption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 *  自定义密码加密功能
 *
 */
@Component
public class MyPasswordEncoder implements PasswordEncoder {

    private String salt;

    @Autowired
    HttpServletRequest request;

    public MyPasswordEncoder() {
        this(-1);
    }

    public MyPasswordEncoder(int strength) {
    }


    /**
     * 用于用户注册时使用
     * 对密码使用随机的密码经行加密，返回加密的值，和加密盐，返回形式如下：“加密值,加密的随机盐”
     * @param rawPassword 传入密码
     *
     * @return  返回加密的密码和随机生成的盐,两者通过,分开。
     */
    public String encodeRandom(CharSequence rawPassword) {
        String randomSalt = setRandomSalt();
        return PasswordEncryption.encryption((String) rawPassword,randomSalt)+","+randomSalt;
    }


    /**
     * 对密码经行加密的函数
     * @param rawPassword 输入的密码
     *
     * @return  加密后返回的密码
     */
    @Override
    public String encode(CharSequence rawPassword) {
        setSalt();
        return PasswordEncryption.encryption((String) rawPassword,getSalt());
    }

    /**
     * 对输入的密码与数据库密码经行对比
     * @param rawPassword 输入的密码
     * @param encodedPassword   数据库中查出来的密码
     *
     * @return  返回对比结果true false
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals((String.valueOf(rawPassword)));
    }


    /**
     * 放回随机加密的盐
     * @return String 随机加密的盐
     */
    public String setRandomSalt(){

        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<6;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    public String getSalt() {
        return salt;
    }

    public void setSalt() {
        this.salt = (String) request.getAttribute("loginSalt");
    }
}
